// pages/addressAdd/addressAdd.js
const app = getApp();
import WxValidate from "../../utils/WxValidate";
Page({
  //获取用户input中输入的值
  timeID: 0, //定时器ID
  handleInput(e) {
    const { name } = e.currentTarget.dataset;
    const { value } = e.detail;
    clearTimeout(this.timeID);
    //清楚timeID对应的定时器，即取消相应函数的执行
    this.timeID = setTimeout(() => {
      switch (name) {
        case "doorNum":
          this.setData({ "addressInfo.doorNum": value });
          break;
        case "name":
          this.setData({ "addressInfo.name": value });
          break;
        case "phone":
          this.setData({ "addressInfo.phone": value });
          break;
      }
    }, 500);
  },
  //是否默认地址
  setSwitch(e) {
    this.setData({ "addressInfo.isDefault": e.detail.value });
  },
  /**
   * 页面的初始数据
   */
  /* 地址描述 */
  addressDescribe() {
    wx.showModal({
      title: "地址需知",
      content: "这里是地址说明具体内容",
      showCancel: false,
    });
  },
  /* 楼栋跳转 */
  selectBuild() {
    wx.navigateTo({
      url: "../building/building",
    });
  },
  data: { addressInfo: null },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { openid } = app.globalData.userInfo;
    if (openid) {
      this.setData({ openid });
    } else {
      wx.showToast({ title: "请先登录", icon: "error" });
      setTimeout(() => {
        wx.switchTab({ url: "../user/person/person" });
      }, 1000);
    }
    //读取缓存
    const addressInfo = wx.getStorageSync("addressInfo");
    this.setData({ addressInfo });
    //加载表单验证规则
    this.initValidate();
  },
  //初始化验证规则
  initValidate() {
    // 验证字段的规则
    const rules = {
      building: { required: true },
      doorNum: { required: true },
      name: { required: true, maxlength: 10 },
      phone: { required: true, tel: true },
    };
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      building: { required: "请选择楼栋" },
      doorNum: { required: "请输入详细地址" },
      name: { required: "请输入收件人姓名", maxlength: "姓名不能超过10个字符" },
      phone: { required: "请输入收件人手机号", tel: "请输入正确的手机号码" },
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages);
  },
  //表单验证错误提示
  showValidateModal(error) {
    wx.showModal({ content: error.msg, showCancel: false });
  },
  //保存表单
  submitForm() {
    //params保存需要验证的数据对象
    const params = this.data.addressInfo;
    // console.log(params);
    //表单验证
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0];
      this.showValidateModal(error);
      return false;
    }
    //加载中
    wx.showLoading();
    //表单验证完毕，接下来向后端发送数据
    wx.request({
      url: `${app.globalData.server}/wxAddressSave`,
      method: "POST",
      data: Object.assign({}, params, { openid: this.data.openid }),
      success: (res) => {
        console.log(res);
        if (res.data === "success") {
          wx.hideLoading();
          //删除地址缓存
          wx.removeStorageSync("addressInfo");
          //提示
          wx.showToast({
            title: "保存成功",
            icon: "success",
          });
          //返回地址列表
          setTimeout(() => {
            wx.navigateBack();
          }, 1000);
        } else {
          //提示
          wx.showToast({ title: "修改失败", icon: "error" });
        }
      },
      fail: (err) => {
        console.log(err);
        wx.hideLoading();
        //提示
        wx.showToast({ title: "修改失败", icon: "error" });
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
